import requests
import pandas as pd

def get_location_data(area):
   api_key = 'f4146d3f3f1e4fd0ba84f5d61efa28cf'
   url = f'https://geoapi.qweather.com/v2/city/lookup?location={area}&key={api_key}'
   response = requests.get(url)
   if response.status_code != 200:
       raise Exception("API请求失败，请检查API密钥和URL")
   location = response.json()['location'][0]
   return location

def get_7day_data(area):
   api_key = 'f4146d3f3f1e4fd0ba84f5d61efa28cf'
   areaid = get_location_data(area)['id']
   url = f'https://devapi.qweather.com/v7/weather/7d?location={areaid}&key={api_key}'
   response = requests.get(url)
   if response.status_code != 200:
       raise Exception("API请求失败，请检查API密钥和URL")
   data = response.json()['daily']
   df = pd.DataFrame(data)
   return df

def translate_column_names(area):
    df = get_7day_data(area)
    column_mapping = {
        'fxDate': '日期',
        'sunrise': '日出时间',
        'sunset': '日落时间',
        'moonrise': '当天月升时间',
        'moonset': '当天月落时间',
        'moonPhase': '月相名称',
        'moonPhaseIcon': '月相图标代码',
        'tempMax': '当天最高温度',
        'tempMin': '当天最低温度',
        'iconDay': '白天天气状况的图标代码',
        'textDay': '白天天气状况',
        'iconNight': '夜间天气状况的图标代码',
        'textNight': '夜间天气状况',
        'wind360Day': '白天风向360角度',
        'windDirDay': '白天风向',
        'windScaleDay': '白天风力等级',
        'windSpeedDay': '白天风速',
        'wind360Night': '夜间风向360角度',
        'windDirNight': '夜间当天风向',
        'windScaleNight': '夜间风力等级',
        'windSpeedNight': '夜间风速',
        'precip': '当天总降水量',
        'uvIndex': '紫外线强度指数',
        'humidity': '相对湿度',
        'pressure': '大气压强',
        'vis': '能见度',
        'cloud': '云量'
    }

    # 删除中文解释中带代码的列
    columns_to_remove = ['iconDay','moonPhaseIcon', 'iconNight' ,'wind360Night','wind360Day']
    df = df.drop(columns_to_remove, axis=1)

    for column in df.columns:
        if column in column_mapping:
            df = df.rename(columns={column: column_mapping[column]})
    df.set_index('日期', inplace=True)
    return df
